package com.example.demo02.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo02.common.AuthAccess;
import com.example.demo02.common.Result;
import com.example.demo02.entity.Product;
import com.example.demo02.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
@CrossOrigin
public class ProductController {

    @Autowired
    private ProductService productService;

    @AuthAccess
    @PostMapping("/add")
    public Result add(@RequestBody Product product) {
        try {
            productService.save(product);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    @AuthAccess
    @PutMapping("/update")
    public Result update(@RequestBody Product product) {
        productService.updateById(product);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        productService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        productService.removeByIds(ids);
        return Result.success();
    }

    @AuthAccess
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Product> productList = productService.list();
        return Result.success(productList);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Product product = productService.getById(id);
        return Result.success(product);
    }


    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(required = false) String productName,
                               @RequestParam(required = false) String productCategory) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        Page<Product> productPage = productService.page(page,
                new QueryWrapper<Product>()
                        .like(productName != null, "product_name", productName)
                        .like(productCategory != null, "product_category", productCategory));
        return Result.success(productPage);
    }
}